package com.linjm.config;


import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.impl.Base64UrlCodec;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getParameter("newToken");
        //把token保存到cookie中
        if(token!=null){
            CookieUtil.setCookie(request,response,"token",token,WebConst.COOKIE_MAXAGE,false);
        }
        if (token==null){
             token = CookieUtil.getCookieValue(request, "token", false);
        }
        if (token!=null){
            //读取token并解密
            Map map = getUserMapByToken(token);
            String nickName = (String) map.get("nickName");
            //保存到作用域
            request.setAttribute("nickName",nickName);
        }
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        LoginRequire methodAnnotation = handlerMethod.getMethodAnnotation(LoginRequire.class);
        if (methodAnnotation!=null){
            String salt = request.getHeader("X-forwarded-for");
            //String salt = "192.168.1.1";
            String result = HttpClientUtil.doGet(WebConst.VERIFY_ADDRESS+"?token=" + token + "&salt=" + salt);
            if ("success".equals(result)){
                //登录过，认证成功，保存userId
                //读取token并解密
                Map map = getUserMapByToken(token);
                String userId = (String) map.get("userId");
                //保存到作用域
                request.setAttribute("userId",userId);
                return true;
            }else{
                if (methodAnnotation.autoRedirect()){
                    //autoRedirect默认是true，则拦截必须先登录
                    String requestURL = request.getRequestURL().toString();
                    String encodeURL = URLEncoder.encode(requestURL, "UTF-8");
                    response.sendRedirect(WebConst.LOGIN_ADDRESS+"?originUrl="+encodeURL);
                    return false;
                }
            }
        }
        return true;
    }
    // 解密token获取map数据
    private Map getUserMapByToken(String token) {
        // 获取中间部分
        String tokenUserInfo = StringUtils.substringBetween(token, ".");
        Base64UrlCodec base64UrlCodec = new Base64UrlCodec();
        byte[] decode = base64UrlCodec.decode(tokenUserInfo);
        String mapJson = null;
        try {
            mapJson = new String(decode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSON.parseObject(mapJson,Map.class);

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }

}
